<template>
  <el-card style="min-height: 420px">
    <template #header>
      <el-space>
        <el-select v-model="storageStore.cssInjectActive" placeholder="Select" style="width: 240px">
          <el-option
            v-for="{ value } in storageStore.cssInjectList"
            :key="value"
            :label="value"
            :value="value"
          >
          </el-option>
        </el-select>
      </el-space>
      <el-button @click="onAdd">添加</el-button>
      <el-button :disabled="!storageStore.cssInjectActive" @click="onRemove">移除</el-button>
    </template>
    <template #default v-if="storageStore.cssInjectActive">
      <Codemirror
        class="css-inject-editor"
        :extensions="extensions"
        :indent-with-tab="true"
        :tab-size="2"
        v-model="cssObject.css"
      />
    </template>
  </el-card>
</template>

<script lang="ts" setup>
import { storageStore, cssObject } from '@shared/context'
import { Codemirror } from 'vue-codemirror'
import { sass } from '@codemirror/lang-sass'
import { oneDark } from '@codemirror/theme-one-dark'
import { ElMessageBox } from 'element-plus'

defineOptions({ name: 'CSSInject' })

const extensions = [sass(), oneDark]

function onAdd() {
  ElMessageBox.prompt('请输入名称', '添加新规则', {
    inputErrorMessage: '请输入 1~10 字字符串',
    inputValidator(text: string) {
      if (storageStore.cssInjectList.find(({ value }) => text === value)) {
        return `${text}已存在`
      }
      return /^.{1,10}$/.test(text)
    },
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(({ value }) => {
    storageStore.cssInjectList.push({
      value: value,
      css: '.yd-highlight {\n\n}'
    })
    storageStore.cssInjectActive = value
  })
}

function onRemove() {
  ElMessageBox.confirm('您将移除当前规则，是否继续？', '移除', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const { cssInjectActive, cssInjectList } = storageStore
    storageStore.cssInjectList = cssInjectList.filter(({ value }) => value !== cssInjectActive)
    storageStore.cssInjectActive = storageStore.cssInjectList[0]?.value ?? ''
  })
}
</script>

<style lang="scss">
.css-inject-editor {
  width: 100%;
  height: 500px;
}
</style>
